<?php

namespace CbjCode\TpGeneral\Library\Auth;

use addons\third\model\Third;
use app\common\model\User;
use app\common\library\Token;
use CbjCode\TpGeneral\Common\Random;
use CbjCode\TpGeneral\Library\WeChat\MiniWeChat;
use think\Db;
use think\Hook;

class UserService
{
    /**
     * 微信小程序注册用户
     *
     * @param mixed $auth auth授权对象
     * @param string $openid openid
     * @param string $nickname 昵称
     * @param string $avatar 头像
     * @param array $extend 扩展参数
     */
    public static function register(&$auth, string $openid = '', string $nickname = '', string $avatar = '', array $extend = [])
    {
        $ip = request()->ip();
        $time = time();
        $params = [
            'nickname'  => $nickname,
            'avatar'    => $avatar,
            'jointime'  => $time,
            'joinip'    => $ip,
            'logintime' => $time,
            'loginip'   => $ip,
            'prevtime'  => $time,
            'status'    => 'normal'
        ];
        $params = array_merge($params,$extend);
        //账号注册时需要开启事务,避免出现垃圾数据
        Db::startTrans();
        try {
            $user = User::create($params,true);
            $_user = User::get($user->id);
            //设置Token
            $token = Random::uuid();
            $keepTime = $auth->keeptime;
            Token::set($token, $user->id, $keepTime);
            $params['openid'] = $openid;
            $params['time'] = $time;
            $params['keeptime'] = $keepTime;
            $data = $_user->toArray();
            $params = array_merge($params,$data);
            //注册成功的事件
            Hook::listen("user_wechat_register_success", $params);
            Db::commit();
        } catch (\Exception $e) {
            $auth->setError($e->getMessage());
            Db::rollback();
            return false;
        }
        $allowFields = $auth->getAllowFields();
        $userinfo = array_intersect_key($data, array_flip($allowFields));
        return array_merge($userinfo, Token::get($token));
    }


    /**
     * 用户登录
     *
     * @param mixed $auth 授权对象
     * @param int $user_id
     * @return boolean
     */
    public static function login(&$auth,int $user_id): bool
    {
        $user = User::get($user_id);
        if (!$user) {
            $auth->setError('暂无此账号');
            return false;
        }
        if ($user->status != 'normal') {
            $auth->setError('此账号已禁用');
            return false;
        }
        //直接登录会员
        $auth->direct($user->id);
        return true;
    }

    /**
     * 微信授权登陆
     *
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/v1/user/weChatLogin)
     * @ApiParams   (name="code", type="string", required=true, description="code")
     * @ApiParams   (name="iv", type="string", required=true, description="iv")
     * @ApiParams   (name="encryptedData", type="string", required=true, description="encryptedData")
     * @ApiParams   (name="nickname", type="string", required=true, description="昵称")
     * @ApiParams   (name="avatar", type="string", required=true, description="头像")
     * @param mixed $auth 授权对象
     * @param array $extend 扩展参数
     * @param bool $isUpdate 判断是否更新昵称和头像
     */
    public static function weChatLogin(&$auth,array $extend = [], bool $isUpdate = false): array
    {
        $request = request();
        $code = $request->param('code');
        $iv = $request->param('iv');
        $encryptedData = $request->param('encryptedData');
        $nickname = $request->param('nickname');
        $avatar = $request->param('avatar');
        $weChat = MiniWechat::instance();
        $weChatAuth = $weChat->getCode($code);
        if(isset($weChatAuth['errcode'])){
            return jsonError('code ERROR',$weChatAuth);
        }
        if(isset($weChatAuth['openid'])){
            $openid = $weChatAuth['openid'];
            $third = Third::get(['openid' => $openid,'platform'=>"wx_app"]);
            if($third){
                $ret = self::login($auth,$third->user_id);
                if($ret){
                    $user = $auth->getUserinfo();
                    if ($nickname&&$avatar&&$isUpdate){
                        if ($user['nickname']!==$nickname||$user['avatar']!==$avatar){
                            $user['nickname']=$nickname;
                            $user['avatar']=$avatar;
                            $model = $auth->getUser();
                            $model->nickname = $nickname;
                            $model->avatar = $avatar;
                            $model->save();
                        }
                    }
                    $data = array_merge($user,$weChatAuth);
                    return jsonSuccess('ok',$data);
                }else{
                    return jsonError($auth->getError());
                }
            }else{
                if ($iv&&$encryptedData){
                    $result = $weChat->encryptor($weChatAuth['session_key'],$iv,$encryptedData);
                    $nickname = $result['nickName'];
                    $avatar = $result['avatarUrl'];
                }
                $res = self::register($auth,$openid,$nickname,$avatar,$extend);
                if ($res!==false) {
                    return jsonSuccess('ok',$res);
                }else{
                    return jsonError($auth->getError());
                }
            }
        }
        return jsonError("请求参数错误");
    }
}